    //
//  ChangePasswordVC.m
//  HengYouCai
//
//  Created by ycgwl on 2017/5/1.
//  Copyright © 2017年 lwj. All rights reserved.
//

#import "ChangePasswordVC.h"
#import "HengYouCai-Swift.h"

@interface ChangePasswordVC ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIButton *forgetBtn;
@property (nonatomic, retain)UITextField *pswNewTF;
@property (nonatomic, retain)UITextField *oldPswTF;

@property (weak, nonatomic) IBOutlet UIButton *okBtn;

@end


@implementation ChangePasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self pswSignale];
    _pswNewTF.delegate = self;
    _oldPswTF.delegate = self;

}
- (void)pswSignale
{
    if (!_isLogin) {
        _pswNewTF.keyboardType = UIKeyboardTypeNumberPad;
        _oldPswTF.keyboardType = UIKeyboardTypeNumberPad;
        
        [self.pswNewTF.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
            if (x.length>6) {
                [self.view showHUDWarnTips:@"请输入6位交易密码" hideDelay:1.5];
//                _okBtn.enabled = NO;
//                [_okBtn setBackgroundColor:Normal_UnselecBtnColor];
            }
        }];
        
    }
   // 登录密码长度大于零 交易密码的长度==6
    RACSignal *newSignal = [self.pswNewTF.rac_textSignal
                                  map:^id(NSString *text) {
                                      
                                      
                                      return _isLogin?@([self isValid:text]):@([self isNewValid:text]);
                                  }];
    // 原密码已经填写
    RACSignal *oldSignal = [self.oldPswTF.rac_textSignal 
                                    map:^id(NSString *text) {
                                        return @([self isValid:text]);
                                    }];
    // 聚合两个信号
    RACSignal *shiMingSignal = [RACSignal combineLatest:@[
                                                         newSignal,
                                                         oldSignal
                                                          ]
                                                 reduce:^id(NSNumber *newPsw, NSNumber *oldPsw) {
                                                     
                                                     return @([newPsw boolValue] && [oldPsw boolValue]);
                                                 }];
    [shiMingSignal subscribeNext:^(NSNumber*okSignal) {
        if ([okSignal boolValue]) {
                _okBtn.enabled = YES;
                [_okBtn setBackgroundColor:Normal_RedColor];
            
        }else{
            _okBtn.enabled = NO;
            [_okBtn setBackgroundColor:Normal_UnselecBtnColor];
            
        }
    }];
}
- (BOOL)isValid:(NSString *)str
{
    return str.length>0;
}
- (BOOL)isNewValid:(NSString *)str
{
    return str.length==6;
}
- (BOOL)isLoginNewValid:(NSString *)str
{
    return str.length>=6;
}
- (void)setUI
{
    

    [_forgetBtn setTitle:_isLogin?@"忘记原登录密码?":@"忘记原交易密码?" forState:UIControlStateNormal];
    self.navigationItem.title = _isLogin?@"修改登录密码":@"修改交易密码";

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PasswordCellID"];
    UIButton *btn = [cell viewWithTag:1003];
    UILabel *titleLab = [cell viewWithTag:1001];
    titleLab.text = indexPath.row==0?@"原密码":@"新密码";
    UITextField *field = [cell viewWithTag:1002];
    if (_isLogin) {
        field.placeholder = indexPath.row==0?@"输入原登录密码":@"设置新登录密码";
        
        
    }else{
        field.placeholder = indexPath.row==0?@"输入原交易密码":@"设置新6位交易密码";

    }
    
    if (indexPath.row==0) {
        self.oldPswTF = field;
    }else{
        self.pswNewTF = field;
    }
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
        btn.selected = !btn.selected;

        [field setSecureTextEntry:!field.secureTextEntry];
    }];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UITextField *field = [cell viewWithTag:1002];
    
    [field becomeFirstResponder];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y<-130) {
        [self.view endEditing:YES];

    }
}
// 确认修改
- (IBAction)changeBtnClick:(UIButton *)sender {
    [self changePassword];
}
// 忘记交易密码
- (IBAction)forget:(UIButton *)sender {
    if (_isLogin) {
        
        GetBackLoginPswVC * vc = [[GetBackLoginPswVC alloc] init];
        vc.phoneNumber = [WLFileManager readUserDataForKey:kUserAccount];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        UIViewController *VC = [[UIStoryboard storyboardWithName:@"Profile" bundle:nil] instantiateViewControllerWithIdentifier:@"GetBackPasswordVCID"];
        [self.navigationController pushViewController:VC animated:YES withHideBottomBarWhenPush:YES pop:YES];
        
    }
    
}
- (void)changePassword
{
    [self.view endEditing:YES];
    [self.tableView showHUDLoading];
    if (_isLogin) {
        [HYCNetService accountUpdateLoginPasswordWithDict:@{@"oldPassword":self.oldPswTF.text,@"newPassword":self.pswNewTF.text} onSuccess:^(NSDictionary *dictResult) {
            //
            [self.tableView showHUDSuccessTips:dictResult[@"message"] hideDelay:1.5];
            [self performSelector:@selector(popTheVC) withObject:nil afterDelay:1];

        } andFailed:^(NSInteger code, NSString *errorMsg) {
            //
            [self.tableView showHUDFailTips:errorMsg hideDelay:1.5];
        }];
    }else{
        [HYCNetService accountUpdateTradePasswordWithDict:@{@"oldTradePassword":self.oldPswTF.text,@"newTradePassword":self.pswNewTF.text} onSuccess:^(NSDictionary *dictResult) {
            //
            [self.tableView showHUDSuccessTips:@"修改交易密码成功！" hideDelay:1];

            [WLFileManager saveUserData:self.pswNewTF.text forKey:kUserPaypassword];
            [self performSelector:@selector(popTheVC) withObject:nil afterDelay:1];
//            [self.navigationController popViewControllerAnimated:YES];
        } andFailed:^(NSInteger code, NSString *errorMsg) {
            //
            [self.tableView showHUDFailTips:errorMsg hideDelay:1.5];

        }];
    }
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (!_isLogin) {
        if (range.location>5) {
            return NO;
        }
        
        
        return YES;
    }
    
    return YES;
}
@end
